package net.qkl.chat.client.msg;

import com.cn.common.core.model.Response;
import com.cn.common.core.session.Session;

import java.util.HashMap;
import java.util.Map;

public class MessageDispatcher implements PacketReceiver {

    public static final int POLICY_REJECT = 2;
    public static final int POLICY_LOG = 1;
    public static final int POLICY_IGNORE = 0;
    private final Map<Short, Map<Short, MessageHandler>> handlers = new HashMap<>();
    private final int unsupportedPolicy;

    public MessageDispatcher() {
        unsupportedPolicy = POLICY_REJECT;
    }

    public MessageDispatcher(int unsupportedPolicy) {
        this.unsupportedPolicy = unsupportedPolicy;
    }

    public void register(Short module, Short cmd, MessageHandler handler) {
        Map<Short, MessageHandler> cmdMap = handlers.get(module);
        if (cmdMap == null) {
            cmdMap = new HashMap<>();
            handlers.put(module, cmdMap);
        }
        cmdMap.put(cmd, handler);
    }

    public MessageHandler unRegister(Short module, Short cmd) {
        Map<Short, MessageHandler> cmdMap = handlers.get(module);
        if (cmd == null) {
            return null;
        }
        return cmdMap.remove(cmd);
    }

    @Override
    public void onReceive(Response packet, Session session) {
        Map<Short, MessageHandler> cmdMap = handlers.get(packet.getModule());
        if (cmdMap == null) {
            return;
        }
        MessageHandler handler = cmdMap.get(packet.getCmd());
        if (handler != null) {
            try {
                handler.handle(packet, session);
            } catch (Exception throwable) {

            }
        }
    }
}
